﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Inscriptionem.Localization;

namespace Inscriptionem.Authorization
{
    public class InscriptionemAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
    {
        public MemberRole[] Roles { get; protected set; }

        public InscriptionemAuthorizeAttribute(params MemberRole[] roles)
        {
            Roles = roles;
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (Roles.Any(r => r == Member.Current.Role))
            {
                return true;
            }

            return base.AuthorizeCore(httpContext);
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException();
            }

            if (!AuthorizeCore(filterContext.HttpContext))
            {
                filterContext.Result = new RedirectResult(string.Format("~/{0}/Login", Language.Current.Value));
            }
        }
    }
}